package com.example.yunJie.digitalSentry.util;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 使用URLConnection连接，调用其他项目的接口
 *
 * @author ymx
 * @date 2022/11/9
 */
public class UrlConnection {
    public static String sendPost(String URL,String parameter, Map<String, String> headers) {
        System.out.println("发起的数据:" + parameter);
        InputStream instr = null;
        java.io.ByteArrayOutputStream out = null;
        BufferedReader br = null;
        StringBuffer buffer = new StringBuffer();
        try {
            java.net.URL url = new URL(URL);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("content-Type", "application/json");
            urlCon.setRequestProperty("charset", "utf-8");
            urlCon.setRequestProperty("accept", "*/*");
            urlCon.setRequestProperty("Connection", "keep-alive");
            byte[] requestParameter = parameter.getBytes();
            urlCon.setRequestProperty("Content-length",String.valueOf(requestParameter.length));
            if (headers != null) {
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    urlCon.setRequestProperty(e.getKey(), e.getValue());
                    System.out.println("e==============    "+e);
                }
            }
//            System.out.println("urlcon--------------------------"+urlCon);
//            OutputStream outputStream = urlCon.getOutputStream();
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(requestParameter);
            printout.flush();
            printout.close();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
            System.out.println("接口返回内容为:" + buffer);
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(out!=null){
                    out.close();
                }
                if(instr!=null){
                    instr.close();
                }
            } catch (Exception ex) {
            }
        }
        return null;
    }


}